package svc

import (
	"time"

	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/config"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type ServiceContext struct {
	Config config.Config
	Db     *gorm.DB
}

func NewServiceContext(c config.Config) *ServiceContext {
	// conn := sqlx.NewMysql(c.DataSource)

	return &ServiceContext{
		Config: c,
		Db:     DbConnect(c),
	}
}

var Db *gorm.DB

func DbConnect(conf config.Config) *gorm.DB {
	var err error
	Db, err = gorm.Open(mysql.Open(conf.DataSource), &gorm.Config{})
	if err != nil {
		panic(err.Error())
	}

	sqlDB, err := Db.DB()

	// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenConns sets the maximum number of open connections to the database.
	sqlDB.SetMaxOpenConns(100)

	// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	sqlDB.SetConnMaxLifetime(time.Hour)

	return Db
}
